package net.zhengxinyun.performance.App.appCtrl;

import com.sirdc.modules.utils.ObjectUtils;
import net.zhengxinyun.performance.App.dto.IndexDTOs.CityIndexDTO;
import net.zhengxinyun.performance.App.dto.IndexUserDTO;
import net.zhengxinyun.performance.App.dto.ScoreDTO;
import net.zhengxinyun.performance.App.dto.report.ReportDTO;
import net.zhengxinyun.performance.App.service.cityIndex.CityIndexService;
import net.zhengxinyun.performance.Util.DataUtil;
import net.zhengxinyun.performance.Util.DateUtils;
import net.zhengxinyun.performance.Util.StringUtils;
import net.zhengxinyun.performance.core.Result;
import net.zhengxinyun.performance.core.ResultUtils;
import net.zhengxinyun.performance.dto.TownIndexDTO;
import net.zhengxinyun.performance.entity.*;
import net.zhengxinyun.performance.filter.CountryIndicatorsFilter;
import net.zhengxinyun.performance.filter.UserFilter;
import net.zhengxinyun.performance.service.department.DepartmentService;
import net.zhengxinyun.performance.service.indicators.CountryIndicatorsService;
import net.zhengxinyun.performance.service.indicators.CountryScoreService;
import net.zhengxinyun.performance.service.indicators.TownScoreService;
import net.zhengxinyun.performance.service.report.IndexReportService;
import net.zhengxinyun.performance.service.workSupervision.WorkScoreService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 综合App 市对县 绩效系统模块
  */
@RestController
@RequestMapping("/app/cityIndex")
public class CityIndexCtrl extends BaseCtrl {

    @Autowired
    private CityIndexService cityIndexService;
    @Autowired
    private CountryIndicatorsService webcityIndexService; // 市对县指标Web service

    @Autowired
    private CountryIndicatorsService contryIndexService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private WorkScoreService workScoreService;
    @Autowired
    private CountryScoreService cityScoreService;

    @Autowired
    private IndexReportService indexReportService;
    @Autowired
    private TownScoreService townScoreService;




    //绩效App 市对县指标管理首页b
    @PostMapping("/cityIndexHome")
    public Result<HashMap<String,Object>> cityIndexHome(@RequestBody CountryIndicatorsFilter filter)
    {
        HashMap<String,Object> dataMap = new HashMap<>();
        filter.setIndexType("二级指标");
        List<CountryIndicatorsFilter> listIndexs = cityIndexService.getAllCityIndex(filter);

        dataMap.put("data",listIndexs);

        System.out.println("接口：/cityIndexHome");
        return ResultUtils.getResults(Result.Status.SUCCESS, "获取市对县指标成功", dataMap);
    }

    @PostMapping("/cityIndexScore")
    public Result<HashMap<String,Object>> cityIndexScore(@RequestBody IndexUserDTO filter)
    {

        String currentYear = getCurrentYear();
        HashMap<String,Object> map = new HashMap<>();
        //根据手机号获取用户信息

        if(filter.getUserPhone()==null)
        {
            return  null;
        }
        String tel  = filter.getUserPhone();
        UserFilter userInfo = getUserInfo(tel);

        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(userInfo,userEntity);
        CountryIndicatorsFilter cindf = new CountryIndicatorsFilter();
        BeanUtils.copyProperties(filter,cindf);
        if(StringUtils.isBlank(cindf.getDateTime()))
        {
            cindf.setDateTime(currentYear);
            cindf.setMonthTime(DateUtils.getLastMonth(currentYear));
        }else {
            cindf.setMonthTime(cindf.getDateTime());
            cindf.setDateTime(cindf.getDateTime().substring(0,4));
        }
        cindf.setIndexType("二级指标");
        List<CountryIndicatorsFilter> countryIndicatorsFilters = contryIndexService.querySecondIndex(cindf, userEntity);

        map.put("data",countryIndicatorsFilters);
        System.out.println("接口：/cityIndexScore");
        return  ResultUtils.getResults(Result.Status.SUCCESS,"数据返回成功",map);
    }


    //创建 指标分析报告
    @PostMapping("/indexrReport")
    public Result<HashMap<String,Object>> indexReport(@RequestBody IndexUserDTO dto)
    {

        String currentYear = getCurrentYear();
        String indexClass = dto.getIndexClass();
        HashMap<String, Object> map = new HashMap<>();
        HashMap<String, Object> page = new HashMap<>();
        String page1 = "", page2 = "", page3 = "", page4 = "",title="";

        int topnum = dto.getTopNum();
        ReportDTO reportFilter = new ReportDTO();
        reportFilter.setIndexClass(Integer.parseInt(indexClass));
        reportFilter.setDatetime(dto.getDateTime());
        List<ReportDTO> old_reports= null;
        switch (indexClass) {
            case "1":
                CountryIndicatorsFilter cityFiter = new CountryIndicatorsFilter();
                if (StringUtils.isBlank(dto.getDateTime())) {
                    cityFiter.setDateTime(currentYear);
                    cityFiter.setMonthTime(DateUtils.getLastMonth(currentYear));

                } else {
                    cityFiter.setDateTime(dto.getDateTime().substring(0, 4));
                    cityFiter.setMonthTime(dto.getDateTime().trim());
                }
                List<CountryIndicatorsFilter> indexScore = cityIndexService.getIndexScore(cityFiter, null);

                List<CountryIndicatorsFilter> goodlist = indexScore.stream().filter(o -> (o.getRank() < topnum && o.getRank() > 0)).collect(Collectors.toList());
                List<CountryIndicatorsFilter> badlist = indexScore.stream().filter(o -> (o.getRank() > topnum)).collect(Collectors.toList());
                List<CountryIndicatorsFilter> noreport = indexScore.stream().filter(o -> (StringUtils.isBlank(o.getAudit()))).collect(Collectors.toList());

                title="关于" + cityFiter.getDateTime() + "市对县绩效考核指标跟踪督查情况的汇报";
                page.put("title",title );

                page1 = "近日，我办对" + cityFiter.getDateTime() + "市对县绩效考核指标运行情况开展督查，现将有关情况汇报如下：";
                page2 = "一、绩效考核指标预计在全市排名前" + topnum + "名的有（共:" + goodlist.size() + "个）：";
                for (CountryIndicatorsFilter item : goodlist) {

                    page2 = page2 + item.getIndexName() + "预计排第" + item.getRank() + "名（" + item.getLeadUnitName() + "）；";

                }
                page3 = "二、绩效考核指标预计排名在第" + topnum + "名之后的共" + badlist.size() + "个：";
                for (CountryIndicatorsFilter item : badlist) {
                    page3 = page3 + item.getIndexName() + "预计排第" + item.getRank() + "名（" + item.getLeadUnitName() + "）；";
                }
                page4 = "三、未报送数据的指标为" + noreport.size() + "共个:";
                for (CountryIndicatorsFilter item : noreport) {
                    page4 = page4 + item.getIndexName() + "（" + item.getLeadUnitName() + "）；";
                }
                page.put("page1", page1);
                page.put("page2", page2);
                page.put("page3", page3);
                page.put("page4", page4);
                map.put("data", page);
                // 保存到报告表

                ReportDTO report = new ReportDTO();
                report.setDatetime(dto.getDateTime());
                report.setTitle(title);
                report.setPage1(page1);
                report.setPage2(page2);
                report.setPage3(page3);
                report.setPage4(page4);
                report.setVaild(0);
                report.setDateYear(dto.getDateTime().substring(0,4));
                report.setIndexClass(1);

                //删除旧的记录
                old_reports = cityIndexService.getReports(reportFilter);
                if(ObjectUtils.isNotBlank(old_reports))
                {
                    cityIndexService.delReport(old_reports.get(0).getId());
                }

                int i = cityIndexService.saveReport(report);
                if(0==i)
                {
                    return ResultUtils.getResults(Result.Status.ERROR,"生成失败",null);
                }
                break;


            case "2":
                //获取21个乡镇
                List<DepartmentEntity> towns = departmentService.selectForDepartment(null, "乡镇");
                for (DepartmentEntity town : towns) {

                 /*   HashMap<String, Object> dataMap = townScoreService.townAnalyse(town.getDepartcode(), dto.getDateTime(), null, dto.getTopNum(), dto.getTopNum());
                    // 保存到报告表
                    String dt = dto.getDateTime();
                    title =town.getDepartAddr()+dto.getDateTime().substring(0,4)+"1-"+dto.getDateTime().substring(dt.length()-2,dt.length())+"月份绩效指标完成情况";
                    String mainword = dataMap.get("mainword").toString();
                    mainword= mainword.replaceAll("该乡镇",town.getDepartAddr());
                    page1=mainword;
                    List<Map<String, Object>> goodindexlists = (List<Map<String, Object>>) dataMap.get("goodIndex");
                    List<Map<String, Object>> badindexlists = (List<Map<String, Object>>)  dataMap.get("badIndex");;


                    page2="完成较好的指标有(共"+goodindexlists.size()+"个):";
                    for (Map<String, Object> item : goodindexlists) {

                        page2=page2+item.get("indexName")+"(第"+item.get("indexRak")+"名);";

                    }
                    page3="排名靠后的指标有(共"+badindexlists.size()+"个):";
                    for (Map<String, Object> item : badindexlists) {

                        page2=page2+item.get("indexName")+"(第"+item.get("indexRak")+"名);";

                    }

                    List<TownIndexDTO>  analys = (List<TownIndexDTO> ) dataMap.get("analy");


                    page.put("page1", page1);
                    page.put("page2", page2);
                    page.put("page3", page3);
                    page.put("page4", analys);
                    map.put("data", page);*/

                    ReportDTO townreport = new ReportDTO();
                    townreport.setDatetime(dto.getDateTime());
                   /* townreport.setTitle(title);
                    townreport.setPage1(page1);
                    townreport.setPage2(page2);
                    townreport.setPage3(page3);
                    townreport.setPage4(page4);*/
                    townreport.setDepartName(town.getDepartAddr());
                    townreport.setDepartCode(town.getDepartcode());
                    townreport.setReportContent(  ""+topnum);
                    townreport.setVaild(1);
                    townreport.setDateYear(dto.getDateTime().substring(0,4));
                    townreport.setIndexClass(Integer.parseInt(indexClass));
                    reportFilter.setDepartCode(town.getDepartcode());
                    old_reports = cityIndexService.getReports(reportFilter);
                    if(ObjectUtils.isNotBlank(old_reports))
                    {
                        cityIndexService.delReport(old_reports.get(0).getId());
                    }

                    int i1 = cityIndexService.saveReport(townreport);
                    if(0==i1)
                    {
                        return ResultUtils.getResults(Result.Status.ERROR,"生成失败",null);
                    }
                    map.put("data","陈强沙雕");


                }





                break;
        }








        System.out.println("接口：/indexrReport");
        return  ResultUtils.getResults(Result.Status.SUCCESS,"数据返回成功",map);
    }

    // 市对县指标详情
    @PostMapping("/indexDetails")
    public Result<HashMap<String,Object>> cityIndexDetails(@RequestBody IndexUserDTO dto)
    {
        if (ObjectUtils.isBlank(dto.getIndexId())) {
            return  ResultUtils.getResults(Result.Status.ERROR,"indexId参数为空",null);
        }

        HashMap<String,Object> map = new HashMap<>();
        String currentYear = getCurrentYear();
        CountryIndicatorsFilter indexFilter = new CountryIndicatorsFilter();
        indexFilter.setIndexType("二级指标");
        indexFilter.setLeadUnit(dto.getDepartcode());
        // 设置日期， 这个日期有点奇葩啊；干
        String dt="";
        if (StringUtils.isBlank(dto.getDateTime())) {
            indexFilter.setMonthTime(DateUtils.getLastMonth(currentYear));
            indexFilter.setDateTime(currentYear);
            dto.setDateTime(DateUtils.getLastMonth(currentYear));
        }else {
            indexFilter.setMonthTime(dto.getDateTime());
            indexFilter.setDateTime(dto.getDateTime().substring(0,4));
            dt=dto.getDateTime();
        }

      //  List<ScoreDTO> scoreDTOS = new ArrayList<>();
        //历史数据
        List<ScoreDTO> yearCityIndex = cityIndexService.getYearCityIndex(dto.getIndexId(),currentYear);

        //当前数据
        HashMap indexdata = new HashMap();
        List<ScoreDTO> collect = yearCityIndex.stream().filter(o -> o.getDatetime().equals(dto.getDateTime())).collect(Collectors.toList());
        if (ObjectUtils.isNotBlank(collect)){
            indexdata.put("finalScore",collect.get(0).getFinalScore()+"");
            indexdata.put("rank",collect.get(0).getRank()+"");
            indexdata.put("question",collect.get(0).getProblems());
            indexdata.put("progress",collect.get(0).getIndexProgress());
        }else {
            indexdata.put("finalScore",0);
            indexdata.put("rank","-");
            indexdata.put("question","");
            indexdata.put("progress","");
        }



        map.put("data",indexdata);
        map.put("historydata",yearCityIndex);

        System.out.println("接口： /indexDetails");
        return  ResultUtils.getResults(Result.Status.SUCCESS,"市指标数据详情返回成功",map);
    }


    //所有市对县的指标

    //管理员页面 市对县指标管理
    @PostMapping("/getCityIndex")
    public Result<HashMap<String,Object>>  indexManageQuery(@RequestBody CountryUnitIndicatorsEntity entity)
    {
        String currentYear = getCurrentYear();

        String tel = entity.getUserPhone();
        UserFilter userInfo = getUserInfo(tel);


        CountryIndicatorsFilter filter = new CountryIndicatorsFilter();
        if(StringUtils.isBlank(entity.getDateTime())){
            entity.setDateTime(currentYear);
        }
        filter.setDateTime(entity.getDateTime());
        filter.setIndexType("二级指标");
        List<CountryIndicatorsFilter> list = webcityIndexService.query(filter);

        List<CountryIndicatorsFilter> newlist  = new ArrayList<>();



        //过滤指标；
        if("admin".equals(userInfo.getUserPermissions())){
            newlist = list;
        }



        HashMap<String,Object> map = new HashMap<>();

        map.put("data",newlist);
        System.out.println("/getCityIndex");
        return ResultUtils.getSuccessResults(map);

    }
    // app 指标增删改
    @PostMapping("/cityIndexManage")
    public Result<String> cityIndexManage(@RequestBody CityIndexDTO entity)
    {

        String optionType = entity.getOptionType();
        if(StringUtils.isBlank(optionType))
        {
            return ResultUtils.getResults(Result.Status.ERROR,"optionType操作类型不能为空");
        }
        String departCode = entity.getDepartCode();


        CountryIndicatorsEntity countryIndicatorsEntity = new CountryIndicatorsEntity();

        Long indexid = entity.getId();
        int code =0;

        switch (entity.getOptionType()){

            case "add":

                BeanUtils.copyProperties(entity,countryIndicatorsEntity);
                countryIndicatorsEntity.setIndexType("二级指标");
                countryIndicatorsEntity.setId(null);
                countryIndicatorsEntity.setAudit(1+"");
                countryIndicatorsEntity.setLeadUnit(entity.getDepartCode());
                code = webcityIndexService.insert(countryIndicatorsEntity);
                if(code==0){
                    System.out.println("失败");
                    return ResultUtils.getResults(Result.Status.ERROR,"id不能为空");
                }

                break;
            case "del":

                if(ObjectUtils.isBlank(indexid))
                {
                    System.out.println("id不能为空");
                    return ResultUtils.getResults(Result.Status.ERROR,"id不能为空");
                }
                countryIndicatorsEntity.setId(indexid);
                String delete = webcityIndexService.delete(countryIndicatorsEntity);
                if(!delete.equals("删除成功"))
                {
                    System.out.println("删除失败");
                    return ResultUtils.getResults(Result.Status.ERROR,"操作失败");
                }

                break;
            case "update":
                if(ObjectUtils.isBlank(indexid))
                {
                    System.out.println("id不能为空");
                    return ResultUtils.getResults(Result.Status.ERROR,"id不能为空");
                }
                entity.setLeadUnit(entity.getDepartCode());
                BeanUtils.copyProperties(entity,countryIndicatorsEntity);

                 code = webcityIndexService.update(countryIndicatorsEntity);
                 if(code ==0)
                 {
                     System.out.println("添加失败");
                     return ResultUtils.getResults(Result.Status.ERROR,"操作失败");
                 }
                break;

        }
        System.out.println("/cityIndexManage");
        return ResultUtils.getSuccessResults("操作成功");
    }


    //获取当前月份所有指标分数
    @PostMapping("/getCityScore")
    public  Result<HashMap<String,Object>> getCityIndexScore(@RequestBody IndexUserDTO dto)
    {
        UserFilter userInfo = getUserInfo(dto.getUserPhone());
        String currentYear = getCurrentYear();
        UserEntity userEntity  = new UserEntity();
        BeanUtils.copyProperties(userInfo,userEntity);
        CountryIndicatorsFilter cityindexFilter = new CountryIndicatorsFilter();
        if(StringUtils.isBlank(dto.getDateTime()))
        {
            cityindexFilter.setDateTime(currentYear);
            cityindexFilter.setMonthTime(DateUtils.getLastMonth(currentYear));
        }else {
            cityindexFilter.setMonthTime(dto.getDateTime());
            cityindexFilter.setDateTime(dto.getDateTime().substring(0,4));
        }


        List<CountryIndicatorsFilter> list = webcityIndexService.querySecondIndex(cityindexFilter,userEntity);

        HashMap<String,Object> map = new HashMap<>();

        map.put("data",list);
        map.put("datetime",cityindexFilter.getMonthTime());
        System.out.println("/getCityScore");
        return  ResultUtils.getSuccessResults(map);
    }




    //指标的得分增删改
    @PostMapping("/cityScoreManage")
    public Result<String> cityScoreMange(@RequestBody CityIndexDTO entity)
    {
        String userPhone = entity.getUserPhone();

        UserFilter userInfo = getUserInfo(userPhone);
        String currentYear = getCurrentYear();
        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(userInfo,userEntity);


        String optionType = entity.getOptionType();
        if(StringUtils.isBlank(optionType)|| StringUtils.isBlank(entity.getDepartCode()) )
        {
            return ResultUtils.getResults(Result.Status.ERROR,"optionType操作类型不能为空或者departCode不能为空");
        }

        int opcode =0;


        int weight = entity.getWeight();
        double rate = entity.getScore();

        //计算得分
        double finalScore = weight*rate/100;
        finalScore= DataUtil.formatNumberDouble(2,finalScore);
        CountryScoreEntity countryScoreEntity = new CountryScoreEntity();
        countryScoreEntity.setFinalScore(finalScore);
        countryScoreEntity.setScore(rate);
        countryScoreEntity.setIndicatorsId(entity.getId()+"" );
        countryScoreEntity.setDateTime(DateUtils.getLastMonth(currentYear));
        countryScoreEntity.setAudit("1");
        countryScoreEntity.setDepartcode(entity.getDepartCode());
        countryScoreEntity.setVaild(1);
        countryScoreEntity.setProblems(entity.getProblems());
        countryScoreEntity.setIndexProgress(entity.getIndexProgress());
        countryScoreEntity.setRank(entity.getRank());


        switch (optionType){
            case "add":
                opcode = cityScoreService.insert(countryScoreEntity);
                //插入前 先判断是否已经填报
                CountryIndicatorsFilter cityfilter = new CountryIndicatorsFilter();
                cityfilter.setIndexId(entity.getIndexId());
                cityfilter.setDateTime(countryScoreEntity.getDateTime().substring(0,4));
                cityfilter.setMonthTime(countryScoreEntity.getDateTime());
                List<CountryIndicatorsFilter> indexScore = cityIndexService.getIndexScore(cityfilter,null);
                if(ObjectUtils.isNotBlank(indexScore)){

                    CountryIndicatorsFilter filter = indexScore.get(0);
                    countryScoreEntity.setId(filter.getId());
                    opcode = cityScoreService.update(countryScoreEntity);

                }
                //填报情况
                if(opcode!=0){
                    indexReportService.saveReport(userEntity,1,entity.getId(),DateUtils.getLastMonth(currentYear)  );
                }
                break;
            case "update":
                if(ObjectUtils.isBlank(entity.getIndexId())){
                    return  ResultUtils.getResults(Result.Status.ERROR,"indexId 不能为空");
                }
                countryScoreEntity.setId(entity.getIndexId()); //indexId 这里为得分表数据的id 不是指标id
                 opcode = cityScoreService.update(countryScoreEntity);
                break;
        }

        if(opcode==0){
            return  ResultUtils.getResults(Result.Status.ERROR,"无数据更新");
        }
        System.out.println("/cityScoreManage");
        return  ResultUtils.getSuccessResults("操作成功");
    }


    @PostMapping("/singleCityIndex")
    public Result<HashMap<String,Object>> getSingleIndexInfo(@RequestBody CityIndexDTO dto)
    {
        HashMap<String ,Object> data = new HashMap<>();


        CountryIndicatorsFilter countryIndicatorsFilter = new CountryIndicatorsFilter();
        countryIndicatorsFilter.setIndexId(dto.getIndexId());
        if(StringUtils.isBlank(dto.getDateTime())){
            ResultUtils.getResults(Result.Status.ERROR,"dateTime参数不能为空");
        }
        countryIndicatorsFilter.setDateTime(dto.getDateTime().substring(0,4));
        countryIndicatorsFilter.setMonthTime(dto.getDateTime());

        ScoreDTO datascore =new ScoreDTO();
        List<CountryIndicatorsFilter> query = webcityIndexService.queryByTwoTable(countryIndicatorsFilter);
        if(!ObjectUtils.isBlank(query)){
            CountryIndicatorsFilter indexscore = query.get(0);

            datascore.setFinalScore( indexscore.getFinalScore());
            //datascore.setDepartName(indexscore.);
            datascore.setDepartName(indexscore.getLeadUnitName());



        }
        List<ScoreDTO> listdto = new ArrayList<>();
        listdto.add(datascore);

        data.put("data",listdto);
        System.out.println("/singleCityIndex");
        return ResultUtils.getSuccessResults(data);

    }


    // 市对县分析报告保存；
    @PostMapping("/saveindexReport")
    public Result<String> saveReport(@RequestBody ReportDTO dto) {


        String optionType = dto.getOptionType(); //1 上传县领导， 0 撤回，0 也是保存


        int indexClass = dto.getIndexClass();
        String datetime = dto.getDatetime();



        if (0 == indexClass || StringUtils.isBlank(datetime) ) {
            return ResultUtils.getResults(Result.Status.ERROR, "indexClass，datetime,reportContent不能为空");
        }
        if (StringUtils.isBlank(optionType)) {
            return ResultUtils.getResults(Result.Status.ERROR, "optionType 不能为空");

        }

        int code =0;

        switch (optionType){
            case "1":
                dto.setVaild(1);
               code   = cityIndexService.updateReport(dto);

                break;
            case "0":
                dto.setVaild(0);
               code = cityIndexService.updateReport(dto);
                break;
            case "del":


              if(indexClass ==2)
              {
                    cityIndexService.delTownReport(indexClass,datetime);
              }else {
                  code =  cityIndexService.delReport(dto.getId());
              }

                break;

        }
        if(0==code){
            return  ResultUtils.getResults("500","无数据更新");
        }





      //  int i = cityIndexService.saveReport(dto);

        System.out.println("/saveindexReport");
        return ResultUtils.getSuccessResults("操作成功");


    }

    // 分析报告保存查看
    @PostMapping("/getIndexReport")
    public Result<HashMap<String,Object>> queeryLeaderReport(@RequestBody ReportDTO dto) {

        int indexClass = dto.getIndexClass();
        List<ReportDTO> reports= new ArrayList<>();
        HashMap<String,Object> map = new HashMap<>();
        dto.setDateYear(getCurrentYear());
        dto.setIndexClass(indexClass);
        reports = cityIndexService.getReports(dto);
        switch (indexClass)
        {
            case 1:

                map.put("data",reports);
                break;
            case 2:
               /* dto.setDateYear(getCurrentYear());
                dto.setIndexClass(indexClass);
                reports = cityIndexService.getReports(dto);*/
                ArrayList<ReportDTO> newReports = reports.stream().collect(Collectors.collectingAndThen(
                        Collectors.toCollection(
                                () -> new TreeSet<>(Comparator.comparing(ReportDTO::getDatetime))
                        ), ArrayList::new

                ));
                map.put("data",newReports);



                break;

        }



         map.put("currentYear",getCurrentYear());
        System.out.println("/getIndexReport");
        return  ResultUtils.getSuccessResults(map);

    }

    /**
     * 乡镇分析报告二级页面
     * @param param
     * @return
     */

    @PostMapping("/townReportlist")
    public Result<HashMap<String, Object>> getTownReport(@RequestBody ReportDTO param)
    {

        int indexClass = param.getIndexClass();
        String datetime = param.getDatetime();

        if(0==indexClass||StringUtils.isBlank(datetime)){

            ResultUtils.getResults(Result.Status.ERROR,"indexClass和datetime不能为空");
        }

        String userPhone = param.getUserPhone();
        UserFilter userInfo = getUserInfo(userPhone);



        ReportDTO dto = new ReportDTO();
        dto.setIndexClass(indexClass);
        dto.setDatetime(datetime);
        if(!"admin".equals(userInfo.getUserPermissions())){
            dto.setDepartCode(userInfo.getDepartcode());
        }

        List<ReportDTO> reports = cityIndexService.getReports(dto);


        HashMap<String,Object> data  = new HashMap<>();

        data.put("data",reports);
        System.out.println("/townReportlist");
        return ResultUtils.getSuccessResults(data);



    }
    //乡镇三级页面
    @PostMapping("/townReportInfo")
    public Result<HashMap<String, Object>> townreportTree(@RequestBody ReportDTO param)
    {

        String page1 = "", page2 = "", page3 = "", page4 = "",title="";
        ReportDTO dto = new ReportDTO();
        HashMap<String,Object> map = new HashMap<>();
        dto.setDatetime(param.getDatetime());
        dto.setIndexClass(param.getIndexClass());
        dto.setDepartCode(param.getDepartCode());

        List<ReportDTO> reports = cityIndexService.getReports(dto);
        if(ObjectUtils.isNotBlank(reports))
        {

            ReportDTO reportDTO = reports.get(0);
            HashMap<String,Object> page = new HashMap<>();
            HashMap<String, Object> dataMap = townScoreService.townAnalyse(reportDTO.getDepartCode(), reportDTO.getDatetime(), null, Integer.parseInt(reportDTO.getReportContent()), Integer.parseInt(reportDTO.getReportContent()));
            // 保存到报告表
            String dt = reportDTO.getDatetime();
            title =reportDTO.getDepartName()+dt.substring(0,4)+"年1-"+reportDTO.getDatetime().substring(dt.length()-2,dt.length())+"月份绩效指标完成情况";
            String mainword = dataMap.get("mainword").toString();
            mainword= mainword.replaceAll("该乡镇",reportDTO.getDepartName());
            page1=mainword;
            List<Map<String, Object>> goodindexlists = (List<Map<String, Object>>) dataMap.get("goodIndex");
            List<Map<String, Object>> badindexlists = (List<Map<String, Object>>)  dataMap.get("badIndex");;


            page2="完成较好的指标有(共"+goodindexlists.size()+"个):";
            for (Map<String, Object> item : goodindexlists) {

                page2=page2+item.get("indexName")+"(第"+item.get("indexRank")+"名);";

            }
            page3="排名靠后的指标有(共"+badindexlists.size()+"个):";
            for (Map<String, Object> item : badindexlists) {

                page3=page3+item.get("indexName")+"(第"+item.get("indexRank")+"名);";

            }

            List<TownIndexDTO>  analys = (List<TownIndexDTO> ) dataMap.get("analy");

            page.put("title",title);
            page.put("page1", page1);
            page.put("page2", page2);
            page.put("page3", page3);
            page.put("page4", analys);
            map.put("data", page);



        }
        System.out.println("/townReportInfo");
        return ResultUtils.getSuccessResults(map);

    }




}
